package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteJydtReleaseBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.manage.CompanyTradesListEntity;
import com.sgb.kjwl.view.ui.adapter.manage.AddViewAdapter;
import com.sgb.kjwl.view.widget.SelectAlbumPopWindow;
import com.sgb.kjwl.view.widget.manage.MImgGetter;
import com.sgb.kjwl.viewmodel.manage.WebsiteUpDataJYDTModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * @author 张驰
 * @date 2021/5/13 17:15
 * @Description 网站发布，经营动态发布功能界面
 * @name com.sgb.kjwl.view.ui.activity.manage
 */
public class WebsiteUpDataJYDTActivity extends WebSiteBuildBaseActivity {

    @Inject
    WebsiteUpDataJYDTModel viewModel;
    private ActivityWebsiteJydtReleaseBinding binding;
    public static final int RESULT_CODE_SELECT = 100; // 返回
    public static final int REQUEST_CODE_SELECT = 101;// 请求

    private String companyNo = ""; //编辑时，编辑编号
    private int siteType = 1; //网站类型  0-个人 1-企业 2-团队 默认为1
    private String title = ""; // 当前编辑的类型
    private boolean isInItView = true;
    //相册选择弹窗
    SelectAlbumPopWindow selectAlbumPopWindow;
    List<LocalMedia> selectionMedia = new ArrayList<>();

    private AddViewAdapter mAddViewAdapter;

    /**
     *
     * @param context
     * @param id 网站编号
     */
    public static void start(Context context,String modelTitle, String id) {
        //网站类型  0-个人 1-企业 2-团队 默认为1
        int siteType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1);
        start(context,modelTitle,id,siteType);
    }

    /**
     * 企业网店 知识产权发布功能界面
     *
     * @param context //     * @param modelTitle 名称
     * @param companyNo 编号
     * @param siteType 编号
     */
    public static void start(Context context, String modelTitle, String companyNo, int siteType) {
        Intent intent = new Intent(context, WebsiteUpDataJYDTActivity.class);
        intent.putExtra("ModelTitle", modelTitle);
        intent.putExtra("companyNo", companyNo);
//        intent.putExtra("siteNo",siteNo);
        intent.putExtra("siteType",siteType);
        context.startActivity(intent);
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule(this)).
                build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(WebsiteUpDataJYDTActivity.this, R.layout.activity_website_jydt_release);
        binding.setViewModel(viewModel);
        title = getIntent().getStringExtra("ModelTitle");
        binding.include.titleView.setText(title + "动态");
        binding.include.ivBack.setOnClickListener(this);
        binding.tvCompanyType.setOnClickListener(this);
        binding.tvUpdate.setOnClickListener(this);
        binding.ivUpdataImage.setOnClickListener(this);
        binding.tvFidleGroup.setOnClickListener(this);
        binding.ivDelect.setOnClickListener(this);
        binding.tvWeb.setOnClickListener(this);
        companyNo = getIntent().getStringExtra("companyNo");
        siteType = getIntent().getIntExtra("siteType", 1);
        binding.etName.setHint(String.format(getResources().getString(R.string.swk_input_hint), "动态"));
        binding.tvCompanyType.setHint(String.format(getResources().getString(R.string.swk_select_type_hint), "动态"));
        //binding.tvName0.setContentText(title + "名称");
        //binding.tvName1.setContentText(title + "类型");
        mAddViewAdapter = new AddViewAdapter(this);
        binding.addView.setAdapter(mAddViewAdapter);
        initDataBack();
    }

    private void initDataBack() {
        viewModel.getMessage().observe(this,new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!TextUtils.isEmpty(s)){
                    MToast.showToast(getActivity(), s);
                    finish();
                    return;
                }
            }
        });
        viewModel.getMutableLiveData().observe(this, new Observer<CompanyTradesListEntity>() {
            @Override
            public void onChanged(CompanyTradesListEntity companyTradesListEntity) {
                setUpdateData(companyTradesListEntity);
                if (companyTradesListEntity.getCustomFieldList() != null && !companyTradesListEntity.getCustomFieldList().isEmpty()){
                    binding.addView.setData(companyTradesListEntity.getCustomFieldList());
                }
            }
        });
        viewModel.getTypePickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "行业分类");
            }
        });
        viewModel.getDynamiPickSelectList().observe(this, new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> pickSelectEntityList) {
                if (isInItView) return;
                if (pickSelectEntityList.size() == 0) {
                    MToast.showToast(getActivity(), "暂无数据");
                    return;
                }
                showOnlyTypeWin(pickSelectEntityList, "动态类型");
            }
        });
        viewModel.getUrlString().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                showAvatar(s);
            }
        });
    }

    private void setUpdateData(CompanyTradesListEntity companyTradesListEntity) {
        binding.setData(companyTradesListEntity);
        if (!TextUtils.isEmpty(companyTradesListEntity.getBody())) {
            binding.tvWeb.setText(Html.fromHtml(companyTradesListEntity.getBody(), new MImgGetter(getActivity(), binding.tvWeb), null));
        }else{
            binding.tvWeb.setText("");
        }
    }

    @Override
    protected void init() {
        if (!TextUtils.isEmpty(companyNo)) {
            viewModel.getCompanyNewsAdminDetailById(getActivity(), companyNo);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_companyType: //动态类型
                isInItView = false;
                if (viewModel.getDynamiPickSelectList().getValue().size() == 0) {
                    viewModel.getDynamicList(getActivity());
                } else {
                    showOnlyTypeWin(viewModel.getDynamiPickSelectList().getValue(), "动态类型");
                }
                break;
            case R.id.tv_update:
                if (!ClickUtils.isDoubleClick()) {
                    Map<String, Object> map = saveOrUpData();
                    if (map == null) return;
                    viewModel.saveCompanyNewsAdminOrUpdate(getActivity(), map);
                }
                break;
            case R.id.tv_fidle_group:  //行业分类
                isInItView = false;
                if (viewModel.getTypePickSelectList().getValue().size() == 0) {
                    viewModel.getAllCategory(getActivity());
                } else {
                    showOnlyTypeWin(viewModel.getTypePickSelectList().getValue(), "行业分类");
                }
                break;
            case R.id.iv_updata_image: //图片上传
                isInItView = false;
                if (selectAlbumPopWindow == null) {
                    initAlbumPop();
                }
                showAlbumPop();
                break;
            case R.id.iv_delect: //清空图片
                isInItView = false;
                showAvatar("");
                break;
            case R.id.web_view: //动态详情
            case R.id.tv_web: //动态详情
                isInItView = false;
                viewModel.getH5Url(getActivity(), viewModel.getMutableLiveData().getValue().getBody(), "quillEditor", REQUEST_CODE_SELECT, "动态详情");
                break;
        }
    }

    private Map<String, Object> saveOrUpData() {
        Map<String, Object> map = new HashMap<>();

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getIndustryNameNo())) {
            MToast.showToast(getActivity(), "请选择行业分类");
            return null;
        }
        //行业分类编号
        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getDynamicTypeNo())) {
            MToast.showToast(getActivity(), "请选择动态类型");
            return null;
        }
        map.put("dynamicTypeNo", viewModel.getMutableLiveData().getValue().getDynamicTypeNo());//动态类型编号
        map.put("industryNameNo", viewModel.getMutableLiveData().getValue().getIndustryNameNo());
        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getTitle())) {
            MToast.showToast(getActivity(), "请输入动态名称");
            return null;
        }
        map.put("title", viewModel.getMutableLiveData().getValue().getTitle());//名称

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getDynamicSummary())) {
            MToast.showToast(getActivity(), "请输入动态摘要");
            return null;
        }
        map.put("dynamicSummary", viewModel.getMutableLiveData().getValue().getDynamicSummary());//动态摘要

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getBody())) {
            MToast.showToast(getActivity(), "请输入动态详情");
            return null;
        }
        map.put("body", viewModel.getMutableLiveData().getValue().getBody());//动态详情

        if (TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getCover())) {
            MToast.showToast(getActivity(), "请上传照片");
            return null;
        }
        map.put("cover", viewModel.getMutableLiveData().getValue().getCover());//图片上传
        map.put("siteType", siteType + "");//网站类型  0-个人 1-企业 2-团队 3-组织
//        map.put("companyNo",);
        if (!TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getId()+"") && 0 != viewModel.getMutableLiveData().getValue().getId()) {
            map.put("id", viewModel.getMutableLiveData().getValue().getId());
        }else{
            map.put("id", "");
        }
        map.put("no", TextUtils.isEmpty(viewModel.getMutableLiveData().getValue().getNo()) ? "" : viewModel.getMutableLiveData().getValue().getNo());
        map.put("customFieldList", mAddViewAdapter.getArrayData());
        return map;
    }

    //单层选择
    private void showOnlyTypeWin(List<PickSelectEntity> selectedDate, String type) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = selectedDate.get(options1).getProjectscale();
            String no = selectedDate.get(options1).getNo();
            switch (type) {
                case "行业分类":
                    viewModel.getMutableLiveData().getValue().setIndustryName(content);
                    viewModel.getMutableLiveData().getValue().setIndustryNameNo(no);
                    break;
                case "动态类型":
                    viewModel.getMutableLiveData().getValue().setDynamicTypeName(content);
                    viewModel.getMutableLiveData().getValue().setDynamicTypeNo(no);
                    break;
            }
            //viewModel.getMutableLiveData().postValue(viewModel.getMutableLiveData().getValue());
            setUpdateData(viewModel.getMutableLiveData().getValue());
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(getResources().getColor(R.color.color_tab_two))
                .setSubmitText("确定")
                .setSubmitColor(getResources().getColor(R.color.color_main)).build();
        businessOption.setPicker(selectedDate);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //展开popuwindw
    private void showAlbumPop() {
        //判断是否在未展示的情况
        if (!selectAlbumPopWindow.isShowing()) {
            //满足条件展示
            selectAlbumPopWindow.showDownPopwindow(binding.grayLayout, true);
        }
    }

    private void initAlbumPop() {
        if (selectAlbumPopWindow == null) {
            //满足条件，创建SelectAlbumPopWindow
            selectAlbumPopWindow = new SelectAlbumPopWindow(this);
        }
        //设置背景
        selectAlbumPopWindow.setBgView(binding.grayLayout);
        //设置点击回调
        selectAlbumPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int type = (int) key1;
                if (type == 0) {
                    pictureSelector(true, 500, 1);
                    selectAlbumPopWindow.dismiss();
                }
            }
        });
    }

    private void showAvatar(String avatar) {
        viewModel.getMutableLiveData().getValue().setCover(avatar);
        viewModel.getMutableLiveData().postValue(viewModel.getMutableLiveData().getValue());
        if (TextUtils.isEmpty(avatar)) {
            binding.ivDelect.setVisibility(View.GONE);
            binding.ivUpdataImage.setImageResource(R.drawable.sck);
        } else {
            binding.ivDelect.setVisibility(View.VISIBLE);
            //Glide展示图片
            Glide.with(this)
                    //加载设置宽高限制
                    .load(avatar + "?x-oss-process=image/resize,m_fixed,h_100")
                    //显示圆图
//                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    //设置为头像
                    .into(binding.ivUpdataImage);
        }
    }

    //结果回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SELECT && resultCode == RESULT_CODE_SELECT) { //经营动态返回
            if (data != null) {
                String body = data.getStringExtra("body").trim();
                viewModel.getMutableLiveData().getValue().setBody(body);
                viewModel.getMutableLiveData().postValue(viewModel.getMutableLiveData().getValue());
            }
        }
    }

    @Override
    protected void onPictureSelectorResult(List<LocalMedia> selectList) {
        // 获取到图片的本地路径
        String path = selectList.get(0).getCompressPath();
        //保存在文件中
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            //接口上传文件
            viewModel.uploadAvatar(getActivity(), file);
        } else {
            MToast.showToast(getApplicationContext(), "获取图片失败！");
        }
    }
}
